/* eslint-disable no-undef */
import * as Minio from "minio"
import moment from "moment"
import { generateUUID } from "."
import { Message } from "element-ui"
const minioClient = new Minio.Client({
  endPoint: minioEndpoint,
  port: minioPort,
  useSSL: false,
  accessKey: minioAccessKey,
  secretKey: minioSecretKey
})
const bucket = "monster-im"
function generateFileName(file) {
  if (file.name.includes("avatar/")) {
    return file.name
  } else {
    const fileName =
      moment().format("YYYY/MM/DD") +
      "/" +
      generateUUID() +
      "." +
      file.name.split(".").slice(-1)

    return fileName
  }
}
/**
 * mino上传文件
 * @export
 * @param {*} file 长传的文件
 * @param {*} [onUploadProgress=() => {}] 进度条
 * @return {*} 上传结果
 */
export function useUploadFile(
  file,
  onUploadProgress = () => {},
  callBackHttp = () => {}
) {
  return new Promise((resolve, reject) => {
    const fileName = generateFileName(file)
    minioClient.presignedPutObject(
      bucket,
      fileName,
      24 * 60 * 60,
      (err, presignedUrl) => {
        if (err) {
          Message({
            message: `上传出错`,
            type: "error"
          })
          reject(err)
          return err
        }
        const config = {
          file,
          filePutUrl: presignedUrl,
          customHeader: {
            "X-FILENAME": fileName
          },
          onUploadProgress,
          onUploaded: () => {
            resolve(fileName)
          },
          onError: ({ error, errorFile }) => {
            console.log(error)
            reject({ error, errorFile })
          }
        }
        const http = createUploadHttp(config)
        callBackHttp(http)
      }
    )
  })
}

//创建上传文件的http
function createUploadHttp(config) {
  const {
    file,
    filePutUrl,
    customHeader,
    onUploadProgress,
    onUploaded,
    onError
  } = config

  let http = new XMLHttpRequest()
  http.upload.addEventListener(
    "progress",
    (e) => {
      //监听http的进度。并执行进度监听函数
      onUploadProgress({
        progressEvent: e,
        uploadingFile: file
      })
    },
    false
  )

  http.onload = () => {
    if ((http.status === 200 && http.status < 300) || http.status === 304) {
      try {
        //监听http的完成事件，并执行上传完成的监听函数
        const result = http.responseURL
        onUploaded({ result })
      } catch (error) {
        //监听错误
        onError({ error, errorFile: file })
      }
    } else {
      onError({ msg: "上传错误", errorFile: file })
    }
  }

  http.open("PUT", filePutUrl, true)
  //加入头信息
  Object.keys(customHeader).forEach((key, index) => {
    http.setRequestHeader(key, customHeader[key])
  })
  http.send(file)
  return http //返回该http实例
}
